﻿using IOP.SgrA;
using IOP.SgrA.Input;
using IOP.SgrA.SilkNet.Vulkan;
using Microsoft.Extensions.Options;
using Silk.NET.Vulkan;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Text;

namespace VkSample102
{
    public class Middleware : IProductionLineMiddleware<SecondaryVulkanRenderGroup>
    {

        public void Invoke(SecondaryVulkanRenderGroup group, RenderingProductionLineDelegate<SecondaryVulkanRenderGroup> next)
        {
            var camera = group.Camera;
            var view = camera.ViewMatrix;
            var project = camera.ProjectionMatrix;
            var cmd = group.SecondaryCommandBuffer;

            CommandBufferInheritanceInfo info = new CommandBufferInheritanceInfo
            {
                Framebuffer = group.Framebuffer.RawHandle,
                OcclusionQueryEnable = false,
                RenderPass = group.RenderPass.RawHandle,
                Subpass = 0
            };
            cmd.Reset();
            cmd.Begin(CommandBufferUsageFlags.CommandBufferUsageOneTimeSubmitBit | 
                CommandBufferUsageFlags.CommandBufferUsageRenderPassContinueBit, info);
            cmd.BindPipeline(PipelineBindPoint.Graphics, group.Pipeline);

            var viewPort = camera.Viewport;
            cmd.SetViewport(new Viewport(viewPort.X, viewPort.Y, viewPort.Width, viewPort.Height, viewPort.MinDepth, viewPort.MaxDepth));
            cmd.SetScissor(new Rect2D(null, new Extent2D((uint)viewPort.Width, (uint)viewPort.Height)));

            int index = 0;
            foreach (var item in group.GetContexts())
            {
                item.SetViewMatrix(in view);
                item.SetProjectionMatrix(in project);
                item.SetCamera(camera);
                group.ItemProductionLine(item);
                if(index != 0) break;
                index++;
            }

            foreach (var child in group.GetChildrens())
            {
                child.GroupRendering();
            }
            cmd.End();
        }
    }
}
